<template>
  <div>
    <el-select clearable  v-model="selectedCategory" placeholder="请选择分类" @change="handleCategoryChange">
      <el-option  v-for="category in flattenCategories" :key="category.id" :label="getCategoryLabel(category)" :value="category.id"></el-option>
    </el-select>
  </div>
</template>

<script>
import api from "@/api/resource";

export default {
  name: 'CategorySelect',
  props: {
    value: {
      type: [String, Number],
      default: ''
    },
  },
  data() {
    return {
      selectedCategory: this.value,
      categories : []
    };
  },
  mounted() {
     this.fetchData()
  },
  computed: {
    flattenCategories() {
      return this.flatten(this.categories);
    }

  },
  watch: {
    value(newValue) {
      this.selectedCategory = newValue;
    },
    selectedCategory(newCategory) {
      this.$emit('input', newCategory);
    }
  },
  methods: {
    fetchData() {
      api.category(this.listQuery).then(response => {
        this.categories = response.data
      })
    },
    flatten(categories, prefix = '') {
      let result = [];
      for (const category of categories) {
        const label = prefix + category.name;
        result.push({ ...category, label });
        if (category.children && category.children.length > 0) {
          result = result.concat(this.flatten(category.children, label + ' / '));
        }
      }
      return result;
    },
    getCategoryLabel(category) {
      return category.label.replace(/\//g, ' / ');
    },
    handleCategoryChange() {
      //console.log('Selected category:', this.selectedCategory);
    }
  }
};
</script>
